package com.kushe.dao;

import com.kushe.config.Config;
import com.kushe.entity.Notice;
import com.kushe.util.core.DataAccess;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;

import java.util.List;

/**
 * Created by WhiteBlue on 15/5/21.
 */
public class NoticeDao extends DataAccess<Notice> {

    @Override
    public Notice get(int id) {
        return null;
    }

    /**
     * 列出留言提示
     *
     * @param user_id 用户id
     */
    public List<Notice> listMessageNew(int user_id) {
        return getDao().query(Notice.class, Cnd.where("user_id", "=", user_id).and("type", "=", 0).and("is_read", "=", 0).limit(5));
    }


    public QueryResult listMyMessage(int user_id, int pageNumber) {
        Pager pager = getDao().createPager(pageNumber, Config.PAGE_SIZE);
        List<Notice> list = getDao().query(Notice.class, Cnd.where("user_id", "=", user_id).and("type", "=", 0));
        return new QueryResult(list, pager);
    }


    /**
     * 列出订单状态提示
     *
     * @param user_id 用户id
     */
    public List<Notice> listOrderNew(int user_id) {
        return getDao().query(Notice.class, Cnd.where("user_id", "=", user_id).and("type", "=", 1).and("is_read", "=", 0).limit(5));

    }

    public void addDesignMessageNotice(int design_id, int user_id) {
        if (!haveMessage(design_id, user_id)) {
            Notice notice = new Notice();
            notice.setDesign_id(design_id);
            notice.setUser_id(user_id);
            notice.setType(0);
            notice.setIs_read(0);
            getDao().insert(notice);
        }
    }

    public void addOrderNotice(int design_id, int user_id) {
        Notice notice = new Notice();
        notice.setDesign_id(design_id);
        notice.setUser_id(user_id);
        notice.setType(1);
        notice.setIs_read(0);
        getDao().insert(notice);
    }


    private boolean haveMessage(int design_id, int user_id) {
        if (getDao().count(Notice.class, Cnd.where("design_id", "=", design_id).and("user_id", "=", user_id).and("type", "=", 0).and("is_read", "=", 0)) > 0) {
            return true;
        } else {
            return false;
        }
    }


    public Notice setRead(int notice_id) {
        Notice notice = getDao().fetch(Notice.class, notice_id);
        if (notice != null) {
            notice.setIs_read(1);
            getDao().update(notice);
        }
        return notice;
    }


}
